﻿using AdminWeb.Areas.Sys.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System.Threading.Tasks;
using XW.Core;
using XW.Data;
using XW.Utils;
using XW.Web.Framework; 

namespace AdminWeb.Areas.Sys.Controllers
{
    /// <summary>
    /// 数据字典控制器
    /// </summary>
    [Area("Sys")]
    [Authorize]
    public class DicController : BaseController
    {
        private readonly SqlSugarRepository<SysDicGrp> _dicGrpRep;
        private readonly ILogger<DicController> _logger;
        private readonly SqlSugarRepository<SysDic> _dicRep;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="dicGrpRep"></param>
        /// <param name="dicRep"></param>
        public DicController(ILogger<DicController> logger
            , SqlSugarRepository<SysDicGrp> dicGrpRep
            , SqlSugarRepository<SysDic> dicRep)
        {
            this._logger = logger;
            this._dicGrpRep = dicGrpRep;
            this._dicRep = dicRep;
        }
        public IActionResult List()
        {
            return View();
        }
        /// <summary>
        /// 分组编辑
        /// </summary>
        /// <returns></returns>
        public IActionResult GrpEdit(long id)
        {
            SysDicGrp grp = null;
            if (id > 0)
            {
                grp = _dicGrpRep.GetById(id);
                if (grp == null)
                {
                    return Content("<h1>分组不存在！</h1>");
                }
            }
            else
            {
                grp = new SysDicGrp();
            }

            //ViewData["CurrentUser"] = user;
            return View(grp);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> GrpPageAsync()
        {
            var pageModel = CommonHelper.GetPageModel4Form<UserPageModel>();
            RefAsync<int> count = 0;
            var query = _dicGrpRep.AsQueryable().Where(d=> !d.IsDelete);
            pageModel.Keyword = pageModel.Keyword.SafeTrim();
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.GrpKey.Contains(pageModel.Keyword) || u.Title.Contains(pageModel.Keyword) || u.Remark.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            else
            {
                query.OrderBy(d => d.Sort);
            }
            // 排序
            var list = await query.ToPageListAsync(pageModel.Page, pageModel.Limit, count);

            return GetSuccessResult(new { items = list, count = count.Value });
        }


        public async Task<IActionResult> GrpSave() {
            long id = CommonHelper.ToInt64(this.Request.Form["id"]);
            string? Title = this.Request.Form["Title"];
            Title = Title.SafeTrim();
            string? GrpKey = this.Request.Form["GrpKey"];
            GrpKey = GrpKey.SafeTrim();
            int IsShow = CommonHelper.ToInt( this.Request.Form["IsShow"]);

            string Remark = CommonHelper.ToString( this.Request.Form["Remark"]).SafeTrim();
            int Sort = CommonHelper.ToInt(this.Request.Form["Sort"]);

            if (GrpKey.SafeTrim().IsNullOrEmpty())
            {
                return GetErrorResult("分组Key不能为空");
            }
            if (Title.IsNullOrEmpty())
            {
                return GetErrorResult("分组名不能为空");
            }
             
            var exists = (await _dicGrpRep.CountAsync(x => x.Id != id && x.GrpKey == GrpKey && !x.IsDelete)) > 0;
            if (exists) { 
                return GetErrorResult("分组Key["+ GrpKey + "]已经存在。");
            }
            if (id == 0)
            {
                 
                var dic = new SysDicGrp();
                dic.Title = Title;
                dic.GrpKey = GrpKey;
                dic.IsShow = IsShow;
                dic.Remark = Remark;
                dic.Sort = Sort;
                _dicGrpRep.Insert(dic);
            }
            else
            {
                _dicGrpRep.AsUpdateable()
                .SetColumns(u => u.Title == Title)
                .SetColumns(u => u.GrpKey == GrpKey)
                .SetColumns(u => u.IsShow == IsShow)
                .SetColumns(u => u.Remark == Remark)
                .SetColumns(u => u.Sort == Sort)
               .setColumnsUpdateUserAndTime()
               .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PageAsync()
        {
            var pageModel = CommonHelper.GetPageModel4Form<DicPageModel>();
            RefAsync<int> count = 0;
            var query = _dicRep.AsQueryable().Where(d => !d.IsDelete);
            pageModel.Keyword = pageModel.Keyword.SafeTrim();
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.DicTitle.Contains(pageModel.Keyword) || u.Remark.Contains(pageModel.Keyword))
                .WhereIF(pageModel.DicGrpId.HasValue && pageModel.DicGrpId >0,
                u => u.DicGrpId == pageModel.DicGrpId);

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            else
            {
                query.OrderBy(d=>d.Sort);
            }
                // 排序
                var list = await query.ToPageListAsync(pageModel.Page, pageModel.Limit, count);

            return GetSuccessResult(new { items = list, count = count.Value });
        }


        /// <summary>
		/// 编辑
		/// </summary>
		/// <returns></returns>
		public IActionResult Edit(long id = 0,long grpid = 0)
        {
            SysDic dic = null;
            if (id > 0)
            {
                dic = _dicRep.GetById(id);
                if (dic == null)
                {
                    return Content("<h1>数据不存在！</h1>");
                }
            }
            else
            {
                dic = new SysDic();
                dic.DicGrpId = grpid;
            }

            //ViewData["CurrentUser"] = user;
            return View(dic);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Save()
        {
            string? DicValue = this.Request.Form["DicValue"];

            string? DicTitle = this.Request.Form["DicTitle"];

            string? Remark = this.Request.Form["Remark"];

            int Sort = CommonHelper.ToInt(this.Request.Form["Sort"]);
            int Status = CommonHelper.ToInt(this.Request.Form["Status"]);
            long DicGrpId = CommonHelper.ToInt64(this.Request.Form["DicGrpId"]); 
            long id = CommonHelper.ToInt64(this.Request.Form["id"]);
            if (DicTitle.IsNullOrEmpty())
            {
                return GetErrorResult("[DicTitle]不能为空");
            }

            if (id == 0)
            {
                SysDic dic = new SysDic();
                dic.DicValue = DicValue;
                dic.DicTitle = DicTitle;
                dic.Remark = Remark;
                dic.DicGrpId = DicGrpId;
                dic.Sort = Sort;
                dic.Status = Status;
                _dicRep.Insert(dic);
            }
            else
            {
                _dicRep.AsUpdateable()
               .SetColumns(u => u.DicValue == DicValue)
               .SetColumns(u => u.DicTitle == DicTitle)
               .SetColumns(u => u.Remark == Remark)
               .SetColumns(u => u.Sort == Sort)
               .SetColumns(u => u.Status == Status)
               .setColumnsUpdateUserAndTime()
               .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");

        }
        /// <summary>
        /// 删除分组
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> GrpDelete(long id = 0)
        {
            var dic = _dicGrpRep.GetById(id);
            if (dic == null)
            {
                return GetErrorResult("数据不存在");
            }
            var result = await _dicGrpRep.DeleteByIdAsync(id);

            // 删除关联的明细数据
            await _dicRep.AsDeleteable().Where(d=>d.DicGrpId == id).ExecuteCommandAsync();

            return GetSuccessResult("操作成功！");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> Delete(long id = 0)
        {
            var dic = _dicRep.GetById(id);
            if (dic == null)
            {
                return GetErrorResult("数据不存在");
            }
            var result = await _dicRep.DeleteByIdAsync(id);

            return GetSuccessResult("操作成功！");
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> BatDelete()
        {
            string ids = Request.Form["ids"];
            if (ids.IsNullOrEmpty())
            {
                return GetErrorResult("请选择需要删除的数据");
            }
            var idlist = ids.Split(',').Select(d => CommonHelper.ToInt64(d)).ToArray();
            var result = await _dicRep.DeleteAsync(d => idlist.Contains(d.Id));
            return GetSuccessResult("操作成功！");
        }
    }
}
